package ru.vpitervip.app.client.place;

import java.util.ArrayList;
import java.util.List;


import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.place.shared.Place;
import com.google.gwt.place.shared.PlaceChangeEvent;
import com.google.gwt.place.shared.PlaceController;
import com.google.gwt.user.client.ui.HasConstrainedValue;

public class MainMenuItemPicker implements ValueChangeHandler<MenuItemPlace>, PlaceChangeEvent.Handler {
	
	private PlaceController placeController;
	private HasConstrainedValue<MenuItemPlace> view;
	

	public MainMenuItemPicker(PlaceController placeController) {
		this.placeController=placeController;
		
	}

	@Override
	public void onPlaceChange(PlaceChangeEvent event) {
		
		
		if (event.getNewPlace() instanceof MenuItemPlace) {
			MenuItemPlace place=(MenuItemPlace)event.getNewPlace();
			 if (place instanceof FlatsPlace) place=new FlatsPlace("");
			 view.setValue(place,false);
		}
		
	}

	@Override
	public void onValueChange(ValueChangeEvent<MenuItemPlace> event) {
		placeController.goTo(event.getValue());
		
	}
	
	public HandlerRegistration register(EventBus eventBus, HasConstrainedValue<MenuItemPlace> view) {
		this.view = view;
		final HandlerRegistration placeRegistration = eventBus.addHandler(PlaceChangeEvent.TYPE, this);
		final HandlerRegistration viewRegistration = view.addValueChangeHandler(this);

		return new HandlerRegistration() {
			public void removeHandler() {
				placeRegistration.removeHandler();
				viewRegistration.removeHandler();
				MainMenuItemPicker.this.view = null;
			}
		};
	}
	
	

	
	
}
